package com.code.test.first.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * https://leetcode.cn/problems/binary-tree-right-side-view/
 * 给定一棵二叉树，想象自己站在它的右侧，按照从顶部到底部的顺序，返回从右侧所能看到的节点值。
 */
public class Code199 {

    public static void main(String[] args) {
        TreeNode left10 = new TreeNode(10, null, null);
        TreeNode right20 = new TreeNode(5, null, null);
        TreeNode left30 = new TreeNode(30, null, null);
        TreeNode right40 = new TreeNode(4, null, null);
        TreeNode left3 = new TreeNode(2, null, right20);
        TreeNode right5 = new TreeNode(3, null, right40);
        TreeNode root = new TreeNode(1, left3, right5);

        List<Integer> ret = rightSideView2(root);
        System.out.println(ret);
    }


    public static List<Integer> rightSideView2(TreeNode root) {

        Queue<TreeNode> que = new LinkedList();
        que.add(root);

        List<Integer> ret = new ArrayList();
        List<List<Integer>> allLevel = new ArrayList();

        while (!que.isEmpty()) {
            List<Integer> level = new ArrayList();

            int queSize = que.size();
            for (int i = 0; i < queSize; i++) {
                TreeNode node = que.poll();

                if (node != null) {
                    level.add(node.val);

                    if (node.left != null)
                        que.add(node.left);
                    if (node.right != null)
                        que.add(node.right);
                }

            }

            ret.add(level.get(level.size() - 1));
        }

        return ret;
    }

    public static List<Integer> rightSideView(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> ret = new ArrayList<>();

        queue.add(root);
        while (!queue.isEmpty()) {

            //这里是每一层的大小，直接圈定好，循环里面再加是为了下一次做准备
            int len = queue.size();
            List<Integer> cur = new ArrayList<>();
            for (int i = 0; i < len; i++) {
                TreeNode node = queue.poll();
                cur.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) queue.add(node.right);
            }
            ret.add(cur.get(cur.size()-1));
        }
        return ret;
    }
}
